package com.example.mall.dao;

import com.example.mall.model.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class OrderDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void insert(Order order) {
        String sql = "insert into `order` (timestamp, buyerID, name, phoneNumber, location, price, status) values (?, ?, ?, ?, ?, ?, ?)";
        jdbcTemplate.update(sql, order.getTimestamp(), order.getBuyerid(), order.getName(), order.getPhonenumber(), order.getLocation(), order.getPrice(), order.getStatus());
    }

    public void delete(Integer id) {
        String sql = "delete from `order` where id = ?";
        jdbcTemplate.update(sql, id);
    }

    public void updateStatus(Order order) {
        String sql = "update `order` set status = ? where id = ?";
        jdbcTemplate.update(sql, order.getStatus(), order.getId());
    }

    public void updatePrice(Order order) {
        String sql = "update `order` set price = ? where id = ?";
        jdbcTemplate.update(sql, order.getPrice(), order.getId());
    }

    public Order getById(Integer id) {
        String sql = "select * from `order` where id = ? lock in share mode";
        RowMapper<Order> rowMapper = new BeanPropertyRowMapper<>(Order.class);
        Order order = null;
        try{
            order = jdbcTemplate.queryForObject(sql, rowMapper, id);
        }
        catch (Exception e) {
            return order;
        }
        return order;
    }

    public Order getByTimestamp(String timestamp) {
        String sql = "select * from `order` where timestamp = ? lock in share mode";
        RowMapper<Order> rowMapper = new BeanPropertyRowMapper<>(Order.class);
        Order order = null;
        try{
            order = jdbcTemplate.queryForObject(sql, rowMapper, timestamp);
        }
        catch (Exception e) {
            return order;
        }
        return order;
    }

    public List<Order> getByBuyerId(Integer aID) {
        String sql = "select * from `order` where buyerID = ? lock in share mode";
        RowMapper<Order> rowMapper = new BeanPropertyRowMapper<>(Order.class);
        return jdbcTemplate.query(sql, rowMapper, aID);
    }

}
